# -*- coding: utf-8 -*-

__author__="Boris Avdeev"
__date__ ="$Mar 8, 2011 10:09:48 AM$"

import sqlite3 as sql
from AFTdata import AFTdata
from UTHdata import UTHdata
import numpy as np

def connect():
    return sql.connect('/raid/work1/Caucasus/db/data.sqlite')

def read_ahe(samples=None):
    """Reads uth data into UTHdata class. Samples is a list of sample names, or
    a comma delimited striing of sample names. If none, all samples are read"""
    if isinstance(samples,str): samples = samples.split(',')
    uth=[]
    if samples is None:
        conn = connect()
        samples = conn.cursor().execute("SELECT DISTINCT sample FROM ahe_sg").fetchall()
        conn.close()
    for sample in samples:
        if isinstance(sample,tuple): sample = str(sample[0])
        try:
            uth.append(UTHdata(sample))
            print
            print "----- " + uth[-1].name
        except KeyError:
            uth.append(None)
    if len(uth)==1: uth = uth[0]

    return uth


def read_aft(samples=None, pull_detrital=True, pull_bad=True):
    """Reads aft data into AFTdata class. Samples is a list of sample names, or
    a comma delimited striing of sample names. If none, all samples are read"""
    if isinstance(samples,str): samples = samples.split(',')
    aft=[]
    table = []
    conn = connect()
    query = "SELECT sample,mean,se,report,report_id FROM ages WHERE method='AFT'"
    if not pull_detrital: query+=" AND comment IS NOT 'detrital'"
    if not      pull_bad: query+=" AND comment IS NOT 'bad'"
    if samples is None:
        table = conn.cursor().execute(query).fetchall()
    else:
        query+=" AND sample=?"  # safety first
        for sample in samples:
            table.append(conn.cursor().execute(query, (sample,)).fetchone())
    conn.close()

    for rec in table:
        if rec is None: aft.append(None)
        else:
            sample,a2z_age,a2z_se,report,report_id = rec
            aft.append(AFTdata("/raid/work1/Caucasus/db/AFT/A%s%sA.AGE" % (report,report_id),
                          "/raid/work1/Caucasus/db/AFT/L%s%sA.A2G" % (report,report_id),
                          new_zeta = False, sample=str(sample)))   #  int(report)>=1145
            #aft[-1].name = str(sample)
            #sa = aft[-1].sample_age
            print
            print "----- " + aft[-1].name
            print " A2Z: %.1f ± %.1f" % (a2z_age, a2z_se)
            print "Pool: %.1f ± %.1f" % aft[-1].pooled_age
            #print "MCMC: %.1f ± %.1f" % sa
    if len(aft)==1: aft = aft[0]
    return aft


def get_alt(samples):
    conn=connect()
    cur = conn.cursor()
    alts=[]
    query = "SELECT alt FROM samples_loc WHERE name=?"
    for sample in samples:
        alts.append(cur.execute(query, (sample,)).fetchone()[0])
    conn.close()
    return np.array(alts)

def get_x(samples):
    conn=connect()
    cur = conn.cursor()
    xys=[]
    query = "SELECT x,y FROM samples_omerc WHERE name=?"
    for sample in samples:
        xys.append(cur.execute(query, (sample,)).fetchone()[0])
    conn.close()
    return np.array(xys)




















